import {Component, OnInit} from '@angular/core';
import {Router, ActivatedRoute} from "@angular/router";
import {ExtendHttpService} from "../../../common/extend-http.service";
import {debounceTime} from "rxjs/operator/debounceTime";
import {Observable} from 'rxjs/Rx';
import {TipService} from "../../services/tip.service";
import {EssService} from "../ess.service";

@Component({
  selector: 'app-inventory',
  templateUrl: './inventory.component.html',
  styleUrls: ['./inventory.component.css']
})
export class InventoryComponent implements OnInit {

  isLoading = false;
  loading = true;
  isFlag = false;
  tipType = 'error';
  totalPage = 1;
  loadMoreFlag = true;
  list = [];
  params = {start: 1, key: ''};


  unitList: any = []; // 入库的单位

  constructor(
    private ext: ExtendHttpService,
    public ess: EssService,
    private router: Router,
    private route: ActivatedRoute,
    private tips: TipService
  ) {
  }

  ngOnInit() {
    this.getData(true);
  }

  getData(searchFlag?: boolean) {
    // if (searchFlag) {
    //   if (!this.params.startTime.trim()) {
    //     this.tipService.change(true, '请选择开始时间');
    //     return;
    //   }
    //   if (!this.params.endTime.trim()) {
    //     this.tipService.change(true, '请选择结束时间');
    //     return;
    //   }
    // }
    this.params.start = this.params.start > 1 ? this.params.start + 1 : 1;
    this.ext.post('/merchantApp/inventory/stock/findStock', this.params).subscribe(response => {
      let data = response.json();
      if (data.code === '0') {
        this.list = data.page.list;
        this.list.forEach(v => {
          v.units = JSON.parse(v.units);
          v.units.forEach(item => {
            if (item.unit === v.unit) {
              item.count = v.num;
              this.calcIt(v.units, item);
              return;
            }
          });
        });
        this.params.start = data.page.pageNumber;
        this.totalPage = data.page.totalPage;
        this.isFlag = true;
        this.loading = false;
      } else {
        this.tipType = 'error';
        this.loading = false;
        this.tips.change(true, this.ess.errTips(data));
      }
    }, error => {
      this.tipType = 'error';
      this.loading = false;
      this.tips.change(true, '系统繁忙，操作失败！');
    });
  }

  // 单位换算
  calcIt(units, it) {
    units.forEach(item => {
      if (item.unit !== it.unit) {
        // console.log(item)
        item.count = Math.ceil((item.conversion / it.conversion) * it.count);
      }
    });
  }

  // 新增库存
  add() {
    this.router.navigate(['/main/ess/inventory/inventory-add'], {queryParams: {id: 0}});
  }

  // 入库
  storage(v) {
    this.router.navigate(['/main/ess/inventory/inventory-in'], {queryParams: {obj: JSON.stringify(v)}});
  }

  // 出库
  outbound(v) {
    this.router.navigate(['/main/ess/inventory/inventory-out'], {queryParams: {obj: JSON.stringify(v)}});
  }

}
